import BlockIcon from '@/components/workflow/block-icon'
import { WorkflowRunningStatus } from '@/components/workflow/types'
import { useWorkFlowStore } from '@/store/workflowStore'
import cn from '@/util/classnames'
import { RiCloseLine, RiMoreFill, RiPlayLargeLine } from '@remixicon/react'
import { Dropdown, Input, MenuProps, Tooltip } from 'antd'
import { cloneDeep, trim } from 'lodash'
import { cloneElement, useEffect, useState } from 'react'
import { useCheckLinkStatus } from '../hooks/use-chek-link'
import { canRunBySingle, checkNodeValidity, isStartOrEnd } from '../utils'
import './style.less'

const NodePanel = ({ id = 'id', data, selected, closePanel = (status: boolean) => {}, children }: any) => {
  const {
    flowVariables,
    deleteNode,
    setVerifying,
    setFlowVariables,
    updateRunType,
    updateSingleRunningInfo,
    clearRunInfo
  } = useWorkFlowStore()
  const { checkLinkStatus } = useCheckLinkStatus()

  const [loadPanel, setLoadPanel] = useState(false)
  const showSelectedBorder = selected
  const panelWidth = 500
  const nodesReadOnly = false

  const [nodeData, setNodeData] = useState({ ...data })
  const [nodeName, setNodeName] = useState(data.title)
  const [nameIsEditing, setNameIsEditing] = useState(false)

  useEffect(() => {
    let currentData = { ...data }
    if (flowVariables[id]) {
      currentData = { ...currentData, ...flowVariables[id] }
      setNodeName(flowVariables[id].title)
    }
    // console.log('>>> NodePanel回显内容更新 data, flowVariables[id], currentData', data, flowVariables[id], currentData)
    setNodeData(cloneDeep(currentData))
    setLoadPanel(true)
  }, [id, flowVariables])
  const reName = () => {
    console.log('rename')
    setNameIsEditing(true)
  }
  const delNode = () => {
    console.log('delNode')
    deleteNode(nodeData.id)
    closePanel()
  }
  const nameChange = val => {
    console.log('nameChange')
    const title = trim(val) ? trim(val) : '大模型'
    setNodeName(title)
    setFlowVariables(id, title, { title })
    setNameIsEditing(false)
  }

  const moreActions: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <div className="flex h-[32px] flex-1 cursor-pointer items-center gap-2 rounded-md py-1" onClick={reName}>
          <span>重命名</span>
        </div>
      )
    },
    {
      key: '2',
      label: (
        <div className="flex h-[32px] flex-1 cursor-pointer items-center gap-2 rounded-md py-1" onClick={delNode}>
          <span>删除</span>
        </div>
      )
    }
  ]

  const singleNodeRun = () => {
    // if (!checkLinkStatus()) {
    //   return false
    // }
    clearRunInfo()
    setVerifying(true)
    updateRunType('single')
    /* 失败 */
    if (!checkNodeValidity(nodeData, nodeData.node_type)) {
      updateSingleRunningInfo(nodeData.id, WorkflowRunningStatus.Invalid)
      // setFlowVariables(nodeData.id, nodeData.title, { ...nodeData })
      return
    }
    /* 打开运行弹窗runDrwaerHid 填参数 */
    setFlowVariables(nodeData.id, nodeData.title, { ...nodeData, runDrwaerHid: 1 })
  }

  return (
    <div
      className={cn(
        'workflow-right-container',
        'fixed right-[0] top-[57px] h-[calc(100vh-57px)] bg-[#ffffff]',
        'overflow-visible  shadow-lg transition-all'
      )}
      style={{
        width: `${panelWidth}px`
      }}
    >
      <div
        className={cn(
          'h-[100%] overflow-y-auto rounded-2xl transition-all',
          showSelectedBorder ? 'border-[1px] border-[#296dff]' : 'border-[1px] border-transparent'
        )}
        style={{
          width: `${panelWidth}px`
        }}
      >
        <div className="sticky top-0 z-10 border-b-[0.5px] border-black/5">
          <div className="flex h-[56px] items-center bg-[#ffffff] px-4 pb-1 pt-1">
            {nodeData?.type === 'tool' && nodeData.model?.logo ? (
              <img
                className=" border-white/2 mr-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg text-white shadow-md"
                src={nodeData.model?.logo}
                alt=""
              />
            ) : (
              <BlockIcon className="mr-1 shrink-0" type={nodeData.type} size="md" />
            )}
            <div className="leading-0 flex w-[320px] px-2 py-[5px]">
              {nameIsEditing ? (
                <div className="nopan nodrag">
                  <Input
                    defaultValue={nodeName}
                    placeholder="请输入"
                    style={{ width: '100%' }}
                    maxLength={8}
                    onBlur={e => nameChange(e.target.value)}
                    draggable="false"
                  />
                </div>
              ) : (
                nodeName
              )}
            </div>
            <div
              className="flex shrink-0 items-center justify-end text-gray-500"
              style={{
                width: '148px'
              }}
            >
              {canRunBySingle(nodeData.type) && !nodesReadOnly && (
                <Tooltip title="运行此步骤" className="mr-1">
                  <div
                    className="mr-1 flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-black/5"
                    onClick={() => {
                      singleNodeRun()
                    }}
                  >
                    <RiPlayLargeLine className="text-text-tertiary h-4 w-4" />
                  </div>
                </Tooltip>
              )}
              {/* <Tooltip title="帮助文档">
                <a
                  href=""
                  target="_blank"
                  className="mr-1 flex h-6 w-6 items-center justify-center rounded-md hover:bg-black/5"
                >
                  <RiBookOpenLine className="h-4 w-4 text-gray-500" />
                </a>
              </Tooltip> */}

              {!isStartOrEnd(nodeData.type) && (
                <div className="flex h-6 w-6  cursor-pointer items-center justify-center rounded-md  hover:bg-black/5">
                  <Dropdown menu={{ items: moreActions }} placement="bottom">
                    <RiMoreFill className={`h-4 w-4 text-gray-500 `} />
                  </Dropdown>
                </div>
              )}

              {!isStartOrEnd(nodeData.type) && <div className="mx-3 h-3.5 w-[1px] bg-[#eaecf0]" />}

              <div className="flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-black/5">
                <RiCloseLine
                  className="text-text-tertiary h-4 w-4"
                  onClick={() => {
                    closePanel()
                  }}
                />
              </div>
            </div>
          </div>
        </div>
        {loadPanel && <div className="px-2 py-2">{cloneElement(children, { id, data: nodeData })}</div>}
      </div>
    </div>
  )
}

export default NodePanel
